package com.hoo.permission.sdk.server.dao.impl;

import com.hoo.permission.sdk.server.dao.ISysRoleUserDao;
import com.hoo.permission.sdk.server.domain.entity.SysRole;
import com.hoo.permission.sdk.server.domain.entity.SysRoleUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 系统-角色用户关系表 Dao层 实现
 * @author 小韩工作室
 * @date 2020-06-28 18:15:48
 */
@Repository
public class SysRoleUserDaoImpl implements ISysRoleUserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /*@Override
    public boolean add(SysRoleUser entity){
        return jdbcTemplate.update("INSERT INTO t_sys_role_user(user_id, role_id) VALUES(?, ?)", entity.getUserId(), entity.getRuleId()) > 0;
    }

    @Override
    public boolean delete(SysRoleUser entity){
        return jdbcTemplate.update("DELETE FROM t_sys_role_user WHERE user_id = ? AND role_id = ?", entity.getUserId(), entity.getRuleId()) > 0;
    }*/

    @Override
    public boolean add(Long userId, List<Long> roleIds) {
        List<Object[]> list = new ArrayList<>();
        if (roleIds != null && userId != null && roleIds.size() > 0) {
            for (Long roleId : roleIds) {
                list.add(new Long[] {userId, roleId});
            }
            return jdbcTemplate.batchUpdate("INSERT INTO t_sys_role_user(user_id, role_id) VALUES(?, ?)", list).length == roleIds.size();
        }
        return false;
    }

    @Override
    public boolean deleteByRoleId(Serializable roleId) {
        return jdbcTemplate.update("DELETE FROM t_sys_role_user WHERE role_id = ?", roleId) > 0;
    }

    @Override
    public boolean deleteByUserId(Serializable userId) {
        return jdbcTemplate.update("DELETE FROM t_sys_role_user WHERE user_id = ?", userId) > 0;
    }

    @Override
    public List<SysRole> getRoles(Serializable userId) {
        if (userId == null) {
            new ArrayList<>();
        }
        return jdbcTemplate.query("SELECT * FROM t_sys_role WHERE id IN(SELECT role_id FROM t_sys_role_user WHERE user_id = ?)", new Object[]{userId},  new BeanPropertyRowMapper<SysRole>(SysRole.class));
    }

    @Override
    public List<Long> getRoleIds(Serializable userId) {
        List<Long> roleIds = jdbcTemplate.queryForList("SELECT role_id FROM t_sys_role_user WHERE user_id = ?", new Object[]{ userId}, Long.class);
        return roleIds == null ? new ArrayList<>() : roleIds;
    }
}
